package org.developer.study.springboot.controller;

import org.apache.log4j.Logger;
import org.developer.study.springboot.exception.BizServiceException;
import org.developer.study.springboot.exception.CommonExceptionInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2017/1/27.
 */
@ControllerAdvice(basePackageClasses = PrimaryController.class)
public class CommonControllerAdvice extends ResponseEntityExceptionHandler {
    @Autowired(required = false)
    private CommonExceptionInter commonExceptionInter;
    private static Logger logger = Logger.getLogger(CommonControllerAdvice.class);
    @ExceptionHandler(Exception.class)
    @ResponseBody
    ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
        String content = commonExceptionInter == null ? ex.getMessage() : commonExceptionInter.responseExcepionContext(ex);
        MediaType type = commonExceptionInter == null ? MediaType.TEXT_PLAIN : commonExceptionInter.responseExceptionType();
        HttpStatus status = null;
        HttpHeaders headers = new HttpHeaders();
        if(ex instanceof BizServiceException) {
            BizServiceException bizServiceException = (BizServiceException) ex;
            status = HttpStatus.valueOf(bizServiceException.getCode());
        }else {
            logger.error(String.format("出现了一个系统异常【%s】",ex.getMessage()));
            status = HttpStatus.INTERNAL_SERVER_ERROR;
        }
        headers.setContentType(type);
        return new ResponseEntity<String>(content,headers,status);
    }

}
